<template>
  <svg v-if="visible" class="connection-preview" :style="connectionPreviewStyle">
    <path :d="connectionPath" stroke="#666" stroke-width="2" fill="none"/>
  </svg>
</template>

<script>
export default {
  name: 'ConnectionPreview',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    startX: {
      type: Number,
      default: 0
    },
    startY: {
      type: Number,
      default: 0
    },
    endX: {
      type: Number,
      default: 0
    },
    endY: {
      type: Number,
      default: 0
    }
  },
  inject: {
    scale: {
      from: 'scale',
      default: () => 1
    },
    translateX: {
      from: 'translateX',
      default: () => 0
    },
    translateY: {
      from: 'translateY',
      default: () => 0
    }
  },
  computed: {
    connectionPreviewStyle() {
      return {
        position: 'fixed',
        left: '0',
        top: '0',
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
        zIndex: 10000 // 设置一个非常高的z-index值，确保连线预览始终显示在所有节点之上
      };
    },
    connectionPath() {
      // 获取当前画布的缩放和平移值
      const currentScale = this.scale();
      const currentTranslateX = this.translateX();
      const currentTranslateY = this.translateY();
      
      // 计算在画布变换下的实际坐标
      const adjustedStartX = this.startX * currentScale + currentTranslateX;
      const adjustedStartY = this.startY * currentScale + currentTranslateY;
      const adjustedEndX = this.endX * currentScale + currentTranslateX;
      const adjustedEndY = this.endY * currentScale + currentTranslateY;
      
      // 计算贝塞尔曲线控制点
      const dx = adjustedEndX - adjustedStartX;
      const dy = adjustedEndY - adjustedStartY;
      
      // 计算连线方向的单位向量
      const distance = Math.sqrt(dx * dx + dy * dy);
      const directionX = distance > 0 ? dx / distance : 1;
      const directionY = distance > 0 ? dy / distance : 0;
      
      // 设置从端点外部开始的偏移距离（以像素为单位）
      const offsetDistance = 10 * currentScale; // 偏移距离随缩放比例变化
      
      // 计算偏移后的起始点坐标
      // 添加固定的水平偏移量(20px)，使连线从输出端点右侧开始
      const horizontalOffset = 20 * currentScale; // 水平偏移量随缩放比例变化
      const offsetStartX = adjustedStartX + horizontalOffset; // 固定向右偏移
      const offsetStartY = adjustedStartY; // 垂直方向保持不变，保持在输出端点的中心
      
      // 重新计算贝塞尔曲线控制点
      const bezierX = Math.abs(adjustedEndX - offsetStartX) * 0.5;
      
      // 返回SVG路径
      return `M ${offsetStartX} ${offsetStartY} 
              C ${offsetStartX + bezierX} ${offsetStartY},
                ${adjustedEndX - bezierX} ${adjustedEndY},
                ${adjustedEndX} ${adjustedEndY}`;
    }
  }
};
</script>

<style>
.connection-preview {
  pointer-events: none;
}
</style>